package com.ferry.wallpaper.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.ferry.wallpaper.domain.User;
import com.ferry.wallpaper.service.UserService;
import com.ferry.wallpaper.utils.DateUtils;
import com.ferry.wallpaper.utils.EmailUtils;
import com.ferry.wallpaper.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
public class SettingController {

    @Autowired
    private UserService userService;

    @GetMapping("/set/{id}")
    public String set(@PathVariable Long id, Model model) {
        User user = userService.get(id);
        model.addAttribute("user",user);
        model.addAttribute("birth", DateUtils.getDate(user.getUserBirth()));
        return "setting";
    }

    @PostMapping("/set/{id}")
    public String set(@PathVariable Long id,
                      String email,
                      String nickName,
                      @RequestParam(defaultValue = "1") Integer sex,
                      String info,
                      String birth,
                      String password, Model model, HttpSession session) {

        User user = userService.get(id);
        if (!StringUtils.isEmpty(email,nickName,info,birth,password)) {
            if (EmailUtils.isValidEmail(email)) {
                DateTime parse = DateUtil.parse(birth);
                if (parse != null){
                    user.setUserEmail(email);
                    user.setUserNickname(nickName);
                    user.setUserSex(sex);
                    user.setUserProfile(info);
                    user.setUserBirth(parse);
                    user.setUserPassword(password);
                    boolean update = userService.update(user);
                    if (update) {
                        session.setAttribute("user",user);
                        model.addAttribute("msg","修改成功");
                    } else {
                        model.addAttribute("msg","修改失败");
                    }
                }
            } else {
                model.addAttribute("msg","邮箱不合法");
            }
        } else {
            model.addAttribute("msg","字段不能为空");
        }
        model.addAttribute("user",user);
        return "setting";
    }

}
